#include "tvoeradio.h"

#ifdef Q_WS_X11

#include <QDesktopWidget>
#include <QX11Info>
#include <X11/Xlib.h>
#include <X11/XF86keysym.h>

#define MMKeyStop XKeysymToKeycode(QX11Info::display(), XF86XK_AudioStop)
#define MMKeyPlay XKeysymToKeycode(QX11Info::display(), XF86XK_AudioPlay)
#define MMKeyNext XKeysymToKeycode(QX11Info::display(), XF86XK_AudioNext)

void TvoeRadio::constructOp()
{
    Display *dpy = QX11Info::display();
    XSync(dpy, 0);
    WId rootWindowId = QApplication::desktop()->winId();
    XGrabKey(dpy, MMKeyStop, 0, rootWindowId, 1, GrabModeAsync, GrabModeAsync);
    XGrabKey(dpy, MMKeyPlay, 0, rootWindowId, 1, GrabModeAsync, GrabModeAsync);
    XGrabKey(dpy, MMKeyNext, 0, rootWindowId, 1, GrabModeAsync, GrabModeAsync);
    XSync(dpy, 0);
}

void TvoeRadio::destructOp()
{
    Display *dpy = QX11Info::display();
    WId rootWindowId = QApplication::desktop()->winId();
    XUngrabKey(dpy, MMKeyStop, 0, rootWindowId);
    XUngrabKey(dpy, MMKeyPlay, 0, rootWindowId);
    XUngrabKey(dpy, MMKeyNext, 0, rootWindowId);
}

bool TvoeRadio::x11EventFilter(XEvent *xevent)
{

    XKeyEvent *keyevent = (XKeyEvent *)xevent;
    if (xevent->type != KeyRelease)
        return false;

    if (keyevent->keycode==MMKeyStop) {
        m_mainWindow.stop();
        return true;
    } else if (keyevent->keycode==MMKeyPlay) {
        m_mainWindow.playPause();
        return false;
    } else if (keyevent->keycode==MMKeyNext) {
        m_mainWindow.next();
        return false;
    }
    return false;
}

#endif
